<?php

class PassesController extends AppController
{

	public $name = 'Passes';
	public $helpers = array();
	public $uses = array('Pass');

	public $modelName = '';
	public $po_domain = '';
	public $url_part  = '';

	function beforeFilter()
	{
		parent::beforeFilter();

		$this->modelName = Inflector::singularize($this->name);
		$this->po_domain = Inflector::underscore($this->name);
		$this->url_part  = 'billing';
		$this->set('po_domain', $this->po_domain);
		$this->set('url_part',  $this->url_part);
		$this->set('modelName', $this->modelName);
		$this->set('PKName',    $this->{$this->modelName}->primaryKey);
		Auth::Access('active');
	}

	function list_of_export()
	{
        $this->params['mode'] = 'export';
        $this->setAction('list_of');
	}

	function list_of()
	{
		vendor('date');
	    $modelName = $this->modelName;
		$PKName    = $this->{$modelName}->primaryKey;
		$po_domain = $this->po_domain;
		$url_part  = $this->url_part;

		$this->pageTitle = strip_tags(__d($po_domain, 'list_title', true));

		vendor('contingencies');
		vendor('order_html');
		vendor('pagination_html');
		vendor('page_of_data');

		$client_id = null;
	    $mode = 'list_of';
		if (Auth::o()->is('admin')) {
    	    if (isset($this->params['client_id'])) {
    	        $client_id = $this->params['client_id'];

        	    $Client =& $this->{$modelName}->getModel('Client'); /* @var $Client Client */
                $client_data = $Client->read(null, $client_id);

        		if (empty($client_data)) {
        			$this->msgError(__d('clients', 'absent', true), @$error_code);
        			$this->redirect("/clients/", null, true);
        			exit();
        		}
        	    $mode = 'admin_by_client';
    	    }
		} else {
    	    $mode = 'client';
    	    $auth_data = Auth::o()->data();
    		$client_id = $auth_data['client_id'];
		}

		switch ($mode) {

	    case 'list_of':
    	    $mode = 'list_of';
		    $this->set('clients_list', $this->{$modelName}->getModel('Client')->generateList());
    		$url_part = "billing";
    		$this->set('by_client', false);
            break;

	    case 'admin_by_client':
		    $mode = 'by_client';
    		$url_part = "clients/{$client_id}/billing";
    		$this->set('by_client', true);
		    $this->set('client_data', $client_data);
    	    $this->MainMenu->setActive($this->MainMenu->findItem("/clients/"));
            break;

	    case 'client':
		    $mode = 'by_client';
    		$url_part = "log";
    		$this->set('by_client', true);
    	    $this->MainMenu->setCurrent($this->MainMenu->findItem("/log/"));
            break;
		}

		$contingencies = new Contingencies();
        $contingencies->model =& $this->{$modelName};
        $contingencies->expects = 'Test | Admin | Client | ClientAdmin | Candidate | Testing | Reporting.Testing | Reporting.Report';

        /////////////////////////////////////////////////////////////
        $ses_war_name = __CLASS__.':'.__FUNCTION__.'_filter'.':'.$mode;
        if (!empty($this->data['Filter'])) {
            if (!empty($this->data['Filter']['submit_reset'])) {
                unset($_SESSION[$ses_war_name]);
                unset($this->data['Filter']);
            } elseif (!empty($this->data['Filter']['submit_apply'])) {
                $_SESSION[$ses_war_name] = $this->data['Filter'];
            }
        }
        $filter = isset($_SESSION[$ses_war_name]) ? $_SESSION[$ses_war_name] : array();
        if (empty($this->data['Filter'])) {
            $this->data['Filter'] = $filter;
        }
        $this->set('filter', $filter);
        /////////////////////////////////////////////////////////////
		$conds = array();
		////////////////////////////////////////////////////////////////////////
		if ($mode == 'by_client') {
			$conds[]["`{$modelName}`.`client_id`"] = $client_id;
		} elseif (!empty($filter['client_id'])) {
			$conds[]["`{$modelName}`.`client_id`"] = $filter['client_id'];
		}
		if (!empty($filter['from_date'])) {
			$conds[]["`{$modelName}`.`created`"] = ">={$filter['from_date']}";
		}
		if (!empty($filter['to_date'])) {
			$conds[]["`{$modelName}`.`created`"] = "<=".Date::getToDateTime($filter['to_date']);
		}
		if (!empty($filter['type'])) {
			$conds[]["`{$modelName}`.`type`"] = $filter['type'];
		}
		if (!empty($filter['tool'])) {
			$conds[]["`{$modelName}`.`test_id`"] = $filter['tool'];
		}
		$contingencies->conditions =& $conds;
		////////////////////////////////////////////////////////////////////////

		$author_field = "`ClientAdmin`.`username`";
		if (Auth::o()->is('admin')) {
    		$author_field = "IF(`{$modelName}`.`admin_id` IS NULL, `ClientAdmin`.`username`, `Admin`.`username`)";
		}
		$type_field = $this->{$modelName}->buildFieldForOrder("`{$modelName}`.`type`", "`{$modelName}_type`", $this->{$modelName}->getTypesList());
        $contingencies->fields = array('*', $author_field." AS `{$modelName}_author`", $type_field);

        $appearence = new OrderHTML();
        $appearence->orderFields = array(
            $PKName => "`{$modelName}`.`{$PKName}`",
            'date' => "`{$modelName}`.`created`",
            'type' => "`{$modelName}_type`",
            'client' => "`Client`.`name`",
            'amount' => "`{$modelName}`.`amount`",
            'author' => "`{$modelName}_author`",
            'tool' => "`Test`.`name`",
            'candidate' => "`{$modelName}`.`candidate_id`",
            'report' => "`{$modelName}`.`reporting_id`",
        );
        $appearence->defaultOrder = Order::parseString('date');
        $appearence->ns = __CLASS__.':'.__FUNCTION__.':'.$mode;
        $appearence->processParams();

        $pagination = new PaginationHTML();
        $pagination->ns = __CLASS__.':'.__FUNCTION__.':'.$mode;
        if (! (!empty($this->params['mode']) && $this->params['mode'] == 'export')) {
            $pagination->defaultLimit = 20;
            $pagination->defaultPage = Pagination::pageLast;
            $pagination->processParams();
        }

        $list = new PageOfData($contingencies, $appearence, $pagination);

		$this->set('list', $list);
		$this->set('mode', $mode);
		$this->set('types_list', $this->Pass->getTypesList());
		$this->set('url_part', $url_part);
		$this->set('tools_list', $this->{$modelName}->getModel('Test')->generateList());

		if (!empty($this->params['mode']) && $this->params['mode'] == 'export') {
            /**
             * Из-за ошибок в IE некоторые файлы нельзя не кешировать
             * @link http://support.microsoft.com/kb/316431/ru
             */
            $this->noCache = false;

		    nodebug();
		    $filename = "pass-report.csv";
		    $charset = Configure::read("csv_charset");
			header("Content-type: text/csv; charset={$charset}; name=\"{$filename}\"");
			header("Content-Disposition: attachment; filename=\"{$filename}\"");
			$this->layout = 'ajax';
			$this->render('export');
		}
	}

	function statistics_export()
	{
        $this->params['mode'] = 'export';
        $this->setAction('statistics');
	}

	function statistics()
	{
		$modelName = $this->modelName;
        $PKName    = $this->{$modelName}->primaryKey;
        $po_domain = $this->po_domain;
        $this->url_part = '/statistics';
        $url_part  = $this->url_part;
        $this->set('url_part', $this->url_part);

        $this->pageTitle = strip_tags(__d($po_domain, 'statistics_title', true));

		vendor('contingencies');
		vendor('order_html');
		vendor('pagination_html');
		vendor('page_of_data');

		$contingencies = new Contingencies();
        $contingencies->model =& $this->{$modelName};
        if (Auth::o()->is('admin')) {
            $contingencies->expects = 'Client';
        } else {
            $contingencies->expects = '';
        }
        $contingencies->fields = array(
            "*",
            "SUM(IF(`{$modelName}`.`type` = 'REFILL_ACCOUNT', `{$modelName}`.`amount`, 0)) AS `income`",
            "SUM(IF(`{$modelName}`.`type` != 'REFILL_ACCOUNT', `{$modelName}`.`amount`, 0)) AS `outcome`",
        );
        $contingencies->conditions = "";
        if (Auth::o()->is('client_admin')) {
            $auth_data = Auth::getUser()->data();
            $client_id = intval($auth_data["client_id"]);
            $contingencies->conditions = "`{$modelName}`.`client_id` = {$client_id} ";
        }
        $contingencies->conditions .= (empty($contingencies->conditions) ? "1" : "")." GROUP BY `{$modelName}`.`client_id`";

        $appearence = new OrderHTML();
        if (Auth::o()->is('admin')) {
            $appearence->orderFields = array(
                'client' => "`Client`.`name`",
                'income' => "`income`",
                'outcome' => "`outcome`",
            );
            $appearence->defaultOrder = Order::parseString('client');
    	}
        $appearence->processParams();

        $pagination = new PaginationHTML();
        $pagination->processParams();

        $list = new PageOfData($contingencies, $appearence, $pagination);

		$this->set('list', $list);

        if (Auth::o()->is('admin')) {
            $this->{$modelName}->rel('Client');
            $total = $this->{$modelName}->find('first', array(
            'fields' => array(
                "SUM(IF(`{$modelName}`.`type` = 'REFILL_ACCOUNT', `{$modelName}`.`amount`, 0)) AS `income`",
                "SUM(IF(`{$modelName}`.`type` != 'REFILL_ACCOUNT', `{$modelName}`.`amount`, 0)) AS `outcome`",
            )));
            if (!empty($total[0])) {
                $this->set('total', $total[0]);
            }
        }

		if (!empty($this->params['mode']) && $this->params['mode'] == 'export') {
            /**
             * Из-за ошибок в IE некоторые файлы нельзя не кешировать
             * @link http://support.microsoft.com/kb/316431/ru
             */
            $this->noCache = false;

		    nodebug();
		    $filename = "statistics-report.csv";
		    $charset = Configure::read("csv_charset");
			header("Content-type: text/csv; charset={$charset}; name=\"{$filename}\"");
			header("Content-Disposition: attachment; filename=\"{$filename}\"");
			$this->layout = 'ajax';
			$this->render('statistics_export');
			exit;
		}
	}
}

?>
